package com.microstation.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;

import java.io.File;
import java.nio.file.Path;
import java.util.concurrent.ConcurrentHashMap;

public class QRCodeUtil {

    //public static void main(String[] args) {
    //    int width = 300;      //图片的宽度
    //    int height = 300;     //图片的高度
    //    System.out.println(createCode(width, height, "你哈哈哈", "E:/QRCODE/code.png"));
    //}

    /**
     * @param width
     * @param height
     * @param content
     * @param filePath 文件路径
     * @return
     */
    public static boolean createCode(int width, int height, String content, String filePath) {
        String format = "png";    //图片的格式
        /**
         * 定义二维码的参数
         */
        ConcurrentHashMap hints = new ConcurrentHashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");    //指定字符编码为“utf-8”
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);  //指定二维码的纠错等级为中级
        hints.put(EncodeHintType.MARGIN, 2);    //设置图片的边距
        /**
         * 生成二维码
         */
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            File file = new File(filePath);
            file.getParentFile().mkdirs();
            MatrixToImageWriter.writeToPath(bitMatrix, format, file.toPath());
            if (file.exists()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
